package com.examination.client.util;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.examination.client.constant.SMSCode;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SendSMS {


    /**
     * 发送验证码
     *
     * @param phone
     * @param randomCode
     */
    protected void sendRandomCode(String phone, Integer randomCode) {
        //发送
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", randomCode);
        String str = JSONUtils.toJSONString(map);
        sendSms(phone, SMSCode.FONT_LOGIN, str);
    }

    public void send(String phone, String code, Map<String, Object> parm) {
        //发送
        String str = JSONUtils.toJSONString(parm);
        sendSms(phone, code, str);
    }

    /**
     * 发送短信
     * @param phone			电话
     * @param code	    	短信模板别名
     * @param parm 		    json字符串
     * @return
     */
    private boolean sendSms(String phone,String code,String parm) {
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAIIcHqy6lnqm89", "NSMuES1fblkDLeLhY4NaDKsUFNjWWY");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "default");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "哈喽优行");
        request.putQueryParameter("TemplateCode", code);
        request.putQueryParameter("TemplateParam", parm);
        try {
            String resultStr = client.getCommonResponse(request).getData();
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            if("OK".equals(jsonObject.getString("Code"))){
                return true;
            }else{
                System.out.println("system 发送短信 error: "+resultStr);
                return false;
            }
        } catch (ServerException e) {
            e.printStackTrace();
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}
